<?php
/**
 * This is the model class for table "{{news}}".
 *
 * The followings are the available columns in table '{{news}}':
 * @property integer $id
 * @property string $keywords
 * @property integer $total_view
 * @property integer $total_like
 * @property integer $total_comment
 * @property integer $status_code
 * @property string $posted_date
 * @property integer $posted_by
 * @property string $create_timezone
 * @property string $create_timestamp
 * @property string $create_datetime
 * @property string $create_date
 * @property string $create_time
 * @property integer $create_by
 * @property string $update_timezone
 * @property string $update_timestamp
 * @property string $update_datetime
 * @property string $update_date
 * @property string $update_time
 * @property integer $update_by
 */
class News extends ActiveRecord {

    public $title_;
    
    public $postedDate_;
    public $url_;
    public $status_;
    public $author_;    

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return News the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{news}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('id_, url_, status_, author_', 'filter', 'filter'=>'trim'),
            
            array('image_', 'file', 'allowEmpty'=>true, 'types'=>'gif,jpg,png', 'maxSize'=>Yii::app()->params['maxImageSize']),
            array('postedDate_', 'date', 'format' => Yii::app()->params['dateFormatRule']),
            array('image_, imageEditor_', 'safe', 'on' => 'adminCreate, adminUpdate'),
            array('id_, keywords_, publish_, status_, author_', 'safe', 'on' => 'userSearch, adminSearch, adminCreate, adminUpdate'),
            
            // compulsory
            array('var_', 'ext.validators.BotDetectionValidator'),
            array('var_', 'safe'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'author' => array(self::BELONGS_TO, 'User', 'posted_by'),
            'creator' => array(self::BELONGS_TO, 'User', 'create_by'),
            'editor' => array(self::BELONGS_TO, 'User', 'update_by'),
            'photo' => array(self::HAS_ONE, 'Gallery', 'module_id', 'scopes' => array('module' => __CLASS__, 'primary', 'accessible')),
            'gallery' => array(self::HAS_MANY, 'Gallery', 'module_id', 'scopes' => array('module' => __CLASS__, 'accessible')),
            'html' => array(self::HAS_ONE, 'Content', 'module_id', 'scopes' => array('module' => __CLASS__, 'language' => $this->defaultLanguage)),
            'defaultHtml' => array(self::HAS_ONE, 'Content', 'module_id', 'scopes' => array('module' => __CLASS__, 'language' => $this->defaultLanguage)),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'keywords_' => Lang::t('news.lbl.keywords'),
            'url_' => Lang::t('news.lbl.url'),
            'status_' => Lang::t('news.lbl.status'),
            'author_'=>Lang::t('news.lbl.author'),
            'publish_' => Lang::t('news.lbl.publish'),
            'image_' => Lang::t('news.lbl.image'),
            'postedDate_'=>Lang::t('news.lbl.posted.date'),
            'title_' => Lang::t('news.lbl.title'),
            'brief_'=>Lang::t('news.lbl.brief'),
            'content_' => Lang::t('news.lbl.content'),
            'tags_' => Lang::t('news.lbl.tags'),
            'sefUrl' => Lang::t('news.lbl.sef.url'),
            'metaTitle_' => Lang::t('news.lbl.meta.title'),
            'metaDescription' => Lang::t('news.lbl.meta.description'),
            'metaKeywords_' => Lang::t('news.lbl.meta.keywords'),
        );
    }

    public function scopes() {
        $t = $this->getTableAlias(false);
        return array(
            'published' => array(
                'condition' => $t.'.status_code = :activeStatus'.$t,
                'params' => array(
                    ':activeStatus'.$t => Option::STATUS_ACTIVE,
                ),
            ),
            'accessible'=>array(
                'condition' => $t.'.status_code <> :deletedStatus'.$t,
                'params' => array(
                    ':deletedStatus'.$t => Option::STATUS_DELETED,
                ),
            ),
        );
    }
    
    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function adminSearch() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.
        $t = $this->getTableAlias(false);
        $criteria = new CDbCriteria;
        $criteria->with=array('html', 'author');
        
        $criteria->compare($t.'.id', $this->id_);
        $criteria->compare('html.title',$this->title_,true);
        $criteria->compare('author.username',$this->author_,true);

        $sort=new CSort;
        $sort->sortVar='sort_';
        $sort->multiSort=true;
        $sort->attributes=array(
            'id_'=>array(
                'asc'=>$t.'.id ASC',
                'desc'=>$t.'.id DESC',
            ),
            'title_'=>array(
                'asc'=>'LOWER(html.title) ASC',
                'desc'=>'LOWER(html.title) DESC',
            ),
            'author_'=>array(
                'asc'=>'LOWER(author.username) ASC',
                'desc'=>'LOWER(author.username) DESC',
            ),
            'postedDate_'=>array(
                'asc'=>'posted_date ASC',
                'desc'=>'posted_date DESC',
            ),
            'publish_'=>array(
                'asc'=>'status_code ASC',
                'desc'=>'status_code DESC',
            ),
        );
        $sort->defaultOrder=implode(',', array(
                $t.'.id DESC',
            ));
        
        if (!empty($criteria->with)){
            $criteria->with = array_unique($criteria->with);
            $criteria->together=true;
        }
        return new ActiveDataProvider($this->accessible(), array(
            'criteria' => $criteria,
            'sort'=>$sort,
            'pagination' => array(
                'pageSize' => Yii::app()->request->getParam('pageSize_', $this->pageSize_),
                'pageVar' => 'page_',
            ),
        ));
    }

    public function userSearch(){
        
        $t = $this->getTableAlias(false);
        $criteria = new CDbCriteria;
        $criteria->with=array('html', 'author');
        
        $criteria->compare($t.'.id', $this->id_);
        $criteria->compare('html.title',$this->title_,true);
        $criteria->compare('author.username',$this->author_,true);
        
        $sort=new CSort;
        $sort->sortVar='sort_';
        $sort->multiSort=true;
        $sort->attributes=array(
            'id_'=>array(
                'asc'=>$t.'.id ASC',
                'desc'=>$t.'.id DESC',
            ),
            'title_'=>array(
                'asc'=>'LOWER(html.title) ASC',
                'desc'=>'LOWER(html.title) DESC',
            ),
            'author_'=>array(
                'asc'=>'LOWER(author.username) ASC',
                'desc'=>'LOWER(author.username) DESC',
            ),
            'postedDate_'=>array(
                'asc'=>'posted_date ASC',
                'desc'=>'posted_date DESC',
            ),
            'publish_'=>array(
                'asc'=>'status_code ASC',
                'desc'=>'status_code DESC',
            ),
        );
        $sort->defaultOrder=implode(',', array(
                $t.'.posted_date DESC',
                $t.'.id DESC',
            ));
        
        return new ActiveDataProvider($this->published(), array(
            'criteria' => $criteria,
            'sort'=>$sort,
            'pagination' => array(
                'pageSize' => Yii::app()->request->getParam('pageSize_', $this->pageSize_),
                'pageVar' => 'page_',
            ),
        ));
    }
    
    public function autoFill() {
        switch ($this->scenario) {
            case 'adminCreate':
                $this->postedDate_=$this->currentPHPDateTime;
                break;

            case 'adminUpdate':
                $this->postedDate_=empty($this->posted_date)? $this->currentPHPDateTime:$this->posted_date;
                $this->postedDate_=date(Yii::app()->params['dateFormat'], strtotime($this->postedDate_));
                $this->status_=$this->statusCode;
                break;
        }
    }
    
    public function getStatusOption($id=null){
        $option = array_intersect_key(Option::recordStatus(), array(
            Option::STATUS_ACTIVE =>'',
            Option::STATUS_ARCHIVED=>'',
        ));
        if($id===null) return $option; return isset($option[$id])? $option[$id]:null;
    }

    protected function beforeSave() {
        if (parent::beforeSave()) {
            switch($this->scenario){
                case 'adminCreate':
                case 'adminUpdate':
                    $this->status_code = empty($this->publish_) ? $this->status_ : Option::STATUS_ACTIVE;
                    $this->posted_date=empty($this->postedDate_)? $this->currentPHPDateTime:$this->postedDate_;
                    $this->posted_date=date('Y-m-d', strtotime($this->posted_date));
                    break;
            }//end switch
            
            if ($this->isNewRecord) {
                $this->setCreateDateTime();
            } else {
                $this->setUpdateDateTime();
            }
            return true;
        }
        else
            return false;
    }

    public function updateLikeCounter(){
        return $this->updateCounters(array('total_like'=>1), 'id=:id', array(':id'=>$this->id));
    }
    
    public function getIsPublish() {
        return in_array($this->status_code, array(
            Option::STATUS_ACTIVE,
            //Option::STATUS_EXPIRED,
        ));
    }
    
    public function getAuthorName() {
        return empty($this->author) ? '-' : $this->author->displayName;
    }

    public function getPostedDate() {
        return empty($this->posted_date)? strtotime($this->create_time): strtotime($this->posted_date);
    }
    
    public function getTotalView(){
        return $this->total_view;
    }
    
    public function getTotalLike(){
        return $this->total_like;
    }
    
    public function getTotalComment(){
        return $this->total_comment;
    }
    
    public function getUrl(){
        switch($this->scenario){
            case 'userSearch':
            default:    // public viewing
                return Yii::app()->createUrl('news/view', array_filter(array(
                    'id'=>$this->id,
                    'title'=>$this->sefUrl,
                )));
                break;
        }
    }
    
    

}//end class